package com.sajus.web.billing.ejb.bean;

import java.net.URL;
import java.util.Date;

import javax.annotation.Resource;
import javax.ejb.Schedule;
import javax.ejb.Stateless;
import javax.ejb.TimerService;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

import org.apache.log4j.Logger;

import com.sajus.billing.client.delegate.BusinessDelegateFactory;

@Stateless(mappedName="SajusBillingTimerBean")
public class SajusBillingTimerBean implements TimerLocal {
	@Resource
	TimerService timerService;
	
	@PersistenceUnit(unitName="MySqlDS")
    protected EntityManagerFactory emf;
	
    protected EntityManager em;

	@Override
	@Schedule(minute="*/10", hour="6", persistent=false)
	public void every15Minutes() {
		TransactionContext context = createTransactionContext();
		TransactionContext.setTransactionContext( context );
		
		try {
			Logger.getLogger( SajusBillingTimerBean.class ).info( "Starting doing charging for usage " + new Date()); 
			BusinessDelegateFactory.getInstance().getServiceTypeManager().doUsageBilling();
			
		} catch (NamingException e) {
			e.printStackTrace();
		} catch ( Exception e ){
			System.out.println("Do Usage failed " + e.getMessage() );
		}
	}
	
	@Override
	@Schedule(minute="*/10", hour="5", persistent=false)
	public void fetchAllDeviceList() {
		TransactionContext context = createTransactionContext();
		TransactionContext.setTransactionContext( context );
		
		try {
			BusinessDelegateFactory.getInstance().getServiceTypeManager().getActivateDevices();
			
		} catch (NamingException e) {
			e.printStackTrace();
		} catch ( Exception e ){
			System.out.println("Do Usage failed " + e.getMessage() );
		}
	}
	
  
	public TransactionContext createTransactionContext() {
		em = emf.createEntityManager();
		TransactionContext context = null;
		context = new TransactionContext( em );
		context.setLocalManaged( true );
		TransactionContext.setTransactionContext( context );
		return context;
	}
	
	@Override
	public void everyMinute() {
		// TODO Auto-generated method stub
		
	}
}
